package com.alnex.es.controller;

import com.alnex.es.service.SearchService;
import com.alnex.es.vo.SearchResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@RequestMapping("search")
@RestController
@CrossOrigin
public class SearchController {

	private static final Logger LOGGER =
			LoggerFactory.getLogger(SearchController.class);

	@Autowired
	private SearchService searchService;

	@Autowired
	private RedisTemplate redisTemplate;

	private static final String redisKey = "HAOKE_HOT_WORD";

	@GetMapping
	public SearchResult search(@RequestParam("keyWord") String keyWord,
	                           @RequestParam(value = "page", defaultValue = "1")
			                           Integer page) {
		//防止爬虫抓取过多的数据
		if (page > 100) {
			page = 1;
		}

		// 查询的数据
		SearchResult searchResult = this.searchService.search(keyWord, page);

		if (searchResult.getTotalPage() <= 1) {
			//需要查询热词,按照得分倒序排序，获取前5条数据
			Set<String> set = this.redisTemplate.opsForZSet().reverseRange(redisKey, 0, 4);
			searchResult.setHotWord(set);
		}

		// 处理热词
		Integer count = ((Math.max(searchResult.getTotalPage(), 1) - 1) * SearchService.ROWS)
				+ searchResult.getList().size();
		// 采用zset方式进行存储，值所对应的得分是数据条数
		this.redisTemplate.opsForZSet().add(redisKey, keyWord, count);
		// 记录日志
		LOGGER.info("[Search]搜索关键词为：" + keyWord + ",果数量为：" + count);

		return searchResult;
	}
}